<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\shop;
use app\admin\service\TriggerService;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Request;
use app\admin\model\shop\Category as CategoryModel;
use app\admin\model\shop\Spec as SpecModel;
/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="管理员管理")
 */
class Category extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'sort' => 'desc',
        'cate_id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CategoryModel();
        $this->SpecModel =new SpecModel();
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model->where($where)->count();
            $list  = $this->model->order($this->sort)->where($where)->select();
            $list= $this->model->getLevel($list);
       
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add($cate_id = null)
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
       
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $pidMenuList = $this->model->getPidMenuList();
        $this->assign('id', $cate_id);
        $this->assign('pidMenuList', $pidMenuList);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($cate_id)
    {   
    
        $row = $this->model->where('cate_id',$cate_id)->find();
    
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            if($row->image!=$post['image']){
                del_image($row->image);
            }
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
               
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $pidMenuList = $this->model->getPidMenuList();
        $this->assign('cate_id', $row->pid);
        $this->assign('pidMenuList', $pidMenuList);
        $this->assign('row', $row);
        return $this->fetch();
    }

 

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($cate_id)
    {
        $row = $this->model->whereIn('cate_id', $cate_id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        $pid=$this->model->whereIn('pid', $cate_id)->select()->toArray();
   
        if($pid){
            $this->error('请先删除子分类');
        }
        try {
            $save = $row->delete();
            foreach ($row as $k => $v) {
                del_image($v['image']);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $save ? $this->success('删除成功') : $this->error($e->getMessage());
    }

    /**
     * 
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            // 'cate_id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        // if (!in_array($post['field'], $this->allowModifyFields)) {
        //     $this->error('该字段不允许修改：' . $post['field']);
        // }
     
        $row = $this->model->where('cate_id',$post['cate_id'])->find();
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }
    public function getCate(){
        $list  = $this->model->field('cate_id,cate_name,pid')->where('is_show',1)->order('cate_id asc')->select()->toArray();
        // $list      = $this->model->buildPidMenu(0,$list);
        $list      = $this->getTreeList($list,0);
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'data'  => $list,
        ];
        return json($data);
    }
    public function getTreeList($array= array(),$pid=0)
    {
        $list = [];
    
        foreach($array as $value) {
            if($value['pid']==$pid){
                $value1['cate_id']=$value['cate_id'];
                $value1['cate_name'] = $value['cate_name'];
                $value1['children'] = $this->getTreeList($array,$value['cate_id']);
                if($value1['children'] == null){  
                    unset($value1['children']);            
                }  
                $list[]=$value1;
            } 
        }
        return $list;
    }

}
